package com.liu.auto;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class TokenTemplate {


    @Autowired
    TokenProperties properties;


    /**
     * 生成token
     * @param payload 用户信息
     * @return  token字符串
     */
    public String generateToken(Map<String,?> payload){
        return JWT.create()
                .withHeader(getHeader())
                .withExpiresAt(getExpireDate())
                .withPayload(payload)
                .sign(Algorithm.HMAC256(properties.getSecret()));
    }


    /**
     * 验证token
     * @param token
     * @return
     */
    public ValidResult validToken(String token){
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(properties.getSecret())).build();
        DecodedJWT decodedJWT = null;

        try {
            decodedJWT = jwtVerifier.verify(token);
        } catch (JWTDecodeException e) {
            return new ValidResult(0, "token无效", null);
        }catch (TokenExpiredException e){
            return new ValidResult(0, "token过期", null);
        }
        return new ValidResult(1, "验证成功", decodedJWT.getClaims());
    }





    Map getPayload() {
        Map map = new HashMap();
        map.put("iss", "by");
        map.put("id", "1");
        map.put("username", "admin");
        map.put("role", "admin");
        return map;
    }



    Map getHeader() {
        Map map = new HashMap();
        map.put("typ", "jwt");
        map.put("alg", "HmacSHA256");
        return map;
    }

    /**
     * 获取过期时间 1分钟有效期
     * @return
     */
    Date getExpireDate() {
        return new Date(System.currentTimeMillis() + properties.getValisTime());
    }


}
